import jimp from "jimp";
import tinycolor from'tinycolor2'
import axios from 'axios'
import {ImageData,createCanvas} from 'canvas'
const fs = require('fs');
export const FONT_WIDTH = 12;
export const FONT_HEIGHT = 12;

export const DEFAULT_AVAILABLE_CHARS = "@#&$%863!i1uazvno~;*^+-. ";
/**
 * 亮度转字符
 * @param brightness
 */
export function grayToText(
  brightness: number,
  chars = DEFAULT_AVAILABLE_CHARS
): string {
  const gap = 255 / chars.length;

  let charIndex = Math.floor(brightness / gap);
  if (charIndex >= chars.length) {
    charIndex = chars.length - 1;
  }
  return chars[charIndex];
}

export default async function chartImg(url,qq,chars = DEFAULT_AVAILABLE_CHARS){
  let flag = true
  
  await axios({
    method: 'get',
    url:url,
    responseType: 'arraybuffer'
  }).then(async (response:any) => {
    
    await jimp.read(response.data).then((image) => {
      if(image.bitmap.width>7000){
        flag = false
        return
      }

      if(image.bitmap.width<4000){
        image.scale(2);  
      }else{
        image.scale(1);
      }
      
      const imageData = new ImageData(
        Uint8ClampedArray.from(image.bitmap.data),
        image.bitmap.width,
        image.bitmap.height
      );
 
      const data = imageData.data;
      const width = imageData.width;
      const height = imageData.height;
      // 创建canvas
      console.log(qq,width,height)
      const canvas = createCanvas(width, height)
      const context = canvas.getContext('2d')
      context.fillStyle = '#ffffff'
      context.fillRect(0, 0, width, height)

      context.fillStyle = '#000000'
      context.font = '10px Arial'
      context.textAlign = 'center'
      const lines:string[] = [];
      for (let h = 0; h < height; h += FONT_HEIGHT) {
        let line = "";
        for (let w = 0; w < width; w += FONT_WIDTH) {
          const i = (w + width * h) * 4;
          const color = new tinycolor({
            r: data[i],
            g: data[i + 1],
            b: data[i + 2],
          });
          let text = grayToText(color.getBrightness(), chars)
          line += text
          context.fillText(text, w, h)
        }
        lines.push(line);
      }
      const buffer = canvas.toBuffer('image/png')
      fs.writeFileSync('D:/mirai/magia-mcl/data/net.mamoe.mirai-api-http/images/chartImg/'+qq+'.png', buffer)
    });
  })
  return flag
}
